﻿using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;

namespace HangerSupport
{
	[Regeneration(RegenerationOption.Manual)]
	public class SeiComLinkageUpdate : IExternalApplication
	{
		Result IExternalApplication.OnShutdown(UIControlledApplication application)
		{
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		Result IExternalApplication.OnStartup(UIControlledApplication application)
		{
			SectionUpdater.GetLinkUpdateHanger();
			this.m_thisAppId = application.ActiveAddInId;
			application.ControlledApplication.DocumentCreated += this.ControlledApplication_DocumentCreated;
			application.ControlledApplication.DocumentOpened += this.ControlledApplication_DocumentOpened;
			application.ControlledApplication.DocumentChanged += this.ControlledApplication_DocumentChanged;
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void ControlledApplication_DocumentChanged(object sender, DocumentChangedEventArgs e)
		{
			Document document = e.GetDocument();
			SeiComLinkageUpdate.m_sectionUpdater = new SectionUpdater(this.m_thisAppId);
			SeiComLinkageUpdate.m_sectionUpdater.Register(document);
			document.DocumentClosing += this.Document_DocumentClosing;
		}

		private void ControlledApplication_DocumentCreated(object sender, DocumentCreatedEventArgs e)
		{
			SeiComLinkageUpdate.m_sectionUpdater = new SectionUpdater(this.m_thisAppId);
			SeiComLinkageUpdate.m_sectionUpdater.Register(e.Document);
			e.Document.DocumentClosing += this.Document_DocumentClosing;
		}

		private void ControlledApplication_DocumentOpened(object sender, DocumentOpenedEventArgs args)
		{
			SeiComLinkageUpdate.m_sectionUpdater = new SectionUpdater(this.m_thisAppId);
			SeiComLinkageUpdate.m_sectionUpdater.Register(args.Document);
			args.Document.DocumentClosing += this.Document_DocumentClosing;
		}

		private void Document_DocumentClosing(object sender, DocumentClosingEventArgs e)
		{
			bool flag = SeiComLinkageUpdate.m_sectionUpdater != null;
			if (flag)
			{
				UpdaterRegistry.UnregisterUpdater(SeiComLinkageUpdate.m_sectionUpdater.GetUpdaterId());
				SeiComLinkageUpdate.m_sectionUpdater = null;
			}
		}

		private AddInId m_thisAppId;

		private static SectionUpdater m_sectionUpdater = null;
	}
}
